﻿namespace BEGDC.CC.Web.EZVisit
{
    #region Using Directives

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Text;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using ASBCC.Database.Entity;
    using ASBCC.Database.Service;
    using ASBCC.Workflow.Client;
    using ASBCC.Workflow.K2Manager;
    using BL.Common;
    using BL.Common.Query;
    using Utility.Castle;
    using Utility.Extensions;
    using Workflow;

    #endregion

    public partial class EZVRequest : WorkflowBasePage, IEZVisitPageAccess
    {
        internal const string EditModePrefix = "edt_";
        internal const string ViewModePrefix = "vw_";

        private readonly IQuery queryService = (IQuery)AppContainer.Instance[ServiceConst.QueryService];

        #region Properties

        protected int AppId
        {
            get
            {
                int appId;

                int.TryParse(this.Request.QueryString["ID"], out appId);

                return appId;
            }
        }

        protected string SessionKey
        {
            get
            {
                if (string.IsNullOrEmpty(this.hidAppKey.Value))
                {
                    // Same session key for existing application, Different for new application
                    string key = this.AppId > 0 ? "EZVRequestApplication_" + this.AppId : DateTime.Now.Ticks.ToString();

                    this.hidAppKey.Value = FormsAuthentication.HashPasswordForStoringInConfigFile(key + this.CurrentUser, "MD5");
                }

                return this.hidAppKey.Value;
            }
        }

        protected EZVisitApplicationTableEntity Application
        {
            get
            {
                return this.Session[this.SessionKey] as EZVisitApplicationTableEntity;
            }
            set
            {
                this.Session[this.SessionKey] = value;
            }
        }

        private string CurrentUser
        {
            get
            {
                return this.UserInfo.NameEN; ;
            }
        }

        #endregion

        #region IEZVisitPageAccess Members

        public EZVisitAccessControl AccessControl { get; set; }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            this.AccessControl = new EZVisitAccessControl(this.UserInfo, this.AppId);

            if (!this.AccessControl.HasViewPermission)
            {
                this.Form1.Visible = false;
                this.lblFooter.Text = @"You were not granted the permission to view this page.<br/> <br/>您没有查看此页面的权限。";
                return;
            }

            if (this.AccessControl.BasicInfoTabView.Visible)
            {
                this.ucBasicInfo.AccessControl = this.AccessControl;
            }

            if (!this.Page.IsPostBack)
            {
                this.InitApplication();
                this.SetSelectedTab();
                this.SetBasicInfoView();
                this.SetBranchAndAccountView();
                this.SetApplicantView();
                this.SetContractView();
                this.SetVisitPlacesView();
                this.SetCustomerView();
                this.SetAltAttendeeView();
                this.SetQuotAttchView();
                this.SetAftReturnView();
                this.SetAttchView();
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                return;
            }

            this.ShowErrorMessages();
        }

        private static bool ValueIncludes(string src, string dest)
        {
            src = ";" + src + ";";
            dest = ";" + dest + ";";
            return src.IndexOf(dest, StringComparison.InvariantCultureIgnoreCase) != -1;
        }

        #region Workflow Relational

        private EZVisitApplicationTableEntity _appFormEntity;

        private EZVisitApplicationTableEntity GetAppFormEntity()
        {
            this._appFormEntity = this.Application;
            if (this._appFormEntity == null)
            {
                EZVisitApplicationTableEntity entity;
                int? appFormId = this.GetAppFormId();
                if (appFormId.HasValue)
                {
                    entity = EZVisitApplicationManager.SelectByKeys(appFormId.Value);
                    if (entity == null)
                    {
                        throw new Exception(string.Format("Failed to Get EZVisit Application instance. ID={0}", appFormId));
                    }
                }
                else
                {
                    entity = new EZVisitApplicationTableEntity
                    {
                        RequesterID = this.UserInfo.EmployeeID,
                        RequesterNo = this.UserInfo.EmployeeNo,
                        RequesterNameEN = this.UserInfo.NameEN,
                        RequesterNameCN = this.UserInfo.NameChinese,
                        Folio = this.GetNewFolio()
                    };
                }
                this._appFormEntity = entity;
            }
            else
            {
                if (this.Application.AppID.HasValue)
                    this._appFormEntity = EZVisitApplicationManager.SelectByKeys(this.Application.AppID.Value);
            }

            return this._appFormEntity;
        }

        #endregion

        #region Init Application

        private void InitApplication()
        {
            this.Application = this.AccessControl.Application ??
                               new EZVisitApplicationTableEntity
                               {
                                   RequesterID = this.UserInfo.EmployeeID,
                                   RequesterNo = this.UserInfo.EmployeeNo,
                                   RequesterNameEN = this.UserInfo.NameEN,
                                   RequesterNameCN = this.UserInfo.NameChinese,
                                   RequesterDept = this.queryService.GetDepartmentByID(this.UserInfo.Department.Value).Description,
                                   RequesterOfficeTel = this.UserInfo.OfficePhone,
                                   RequesterMobile = this.UserInfo.Mobile,
                                   RequesterTitle = this.UserInfo.Title,
                                   CreateAt = DateTime.Now,
                                   CreateBy = this.CurrentUser,
                                   IsEnabled = true
                               };

            if (this.Application.AppNo.IsNotNullOrWhiteSpace())
            {
                this.lbAppNo.Text = this.lblAppNo.Text = "&nbsp;&nbsp;Application No：" + this.Application.AppNo;
            }

            if (this.Application.FNCControllerDate != null)
            {
                this.lblReqNo.Text = "&nbsp;&nbsp;EZVisit No：" + this.Application.EZVisitReqNo;
                this.lbAppNo.Visible = false;
                this.lblAppNo.Visible = true;
            }
        }

        #endregion

        #region PostBack Handlers

        private void ShowErrorMessages()
        {
            string ev = this.Request.Form["__EVENTTARGET"];

            if (ev.IsNotNullOrWhiteSpace())
            {
                // Note: Only accept PostBacks from buttons.
                var ctrl = this.Page.FindControl(ev) as IButtonControl;

                if (ctrl == null || !ctrl.CausesValidation)
                {
                    return;
                }
            }
            else
            {
                return;
            }

            if (this.IsValid)
            {
                return;
            }

            // Output the error message.
            var errorMessage = new StringBuilder("<script type='text/javascript'>alert('");

            foreach (BaseValidator validator in this.Validators.Cast<BaseValidator>().Where(v => v.Enabled && !v.IsValid))
            {
                errorMessage.AppendFormat(@"{0}", validator.ErrorMessage);
            }

            errorMessage.Append("');</script>");

            ScriptManager.RegisterStartupScript(this, typeof(IValidator), "ValidateSubmit", errorMessage.ToString(), false);
        }

        private void ReloadDataGrids(string eventTarget)
        {
            switch (eventTarget.ToLowerInvariant())
            {
                case "contractinfo":
                    this.ucContract.BindContractInfo();
                    break;
                case "customer":
                    this.ucCustomer.BindCustomers();
                    break;
                case "altattendee":
                    this.ucAltAttendee.BindAltAttendees();
                    break;
                case "visa":
                    this.ucVisit.BindVisa();
                    this.ucAttachment.BindAttachments();
                    break;
                case "pdcquotation":
                    this.ucQuotAttch.BindQuotation();
                    this.ucAttachment.BindAttachments();
                    break;
                case "contract":
                case "contractexecutionletter":
                case "agenda":
                case "budget":
                case "taquotation":
                case "hostconfirmation":
                case "others":
                    this.ucAttachment.BindAttachments();
                    break;
                case "agendachanged":
                case "customerchanged":
                    this.ucAftAttchment.BindAttachments(true);
                    this.ucAttachment.BindAttachments();
                    break;
                case "hostposttripconfirmationdomestic":
                case "hostposttripconfirmationoversea":
                case "tasettlement":
                case "ezvisitreapprovalmail":
                    this.ucAftAttchment.BindAttachments(false);
                    this.ucAttachment.BindAttachments();
                    break;
            }
        }

        protected void btnReload_Click(object sender, EventArgs e)
        {
            // Postback used for reloading data grids.
            //this.ReloadDataGrids(this.Request.Form["__EVENTTARGET"]);

            this.ReloadDataGrids(this.hidEventTarget.Value);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (this.Application != null && this.Application.AppID == null)
            {
                var catBranchInfo = this.ddlCATBranch.SelectedValue.Split(';');
                this.Application.AllDept = catBranchInfo[3];
                this.Application.Account = this.ddlAccount.SelectedValue;
            }
        }

        #endregion

        #region Selected Tab

        private void SetSelectedTab()
        {
            this.hidSelectedTab.Value = this.AccessControl.SelectedTab.ToString();

            if (this.AccessControl.BasicInfoTabView.Visible || !this.AccessControl.ApplicantTabView.Editable)
            {
                return;
            }

            var prevTab = this.Request.Cookies["prevTab"];

            if (prevTab == null)
            {
                prevTab = new HttpCookie("prevTab") { Value = this.hidSelectedTab.Value, Expires = DateTime.Now.AddMinutes(10) };

                this.Response.Cookies.Add(prevTab);
            }
            else
            {
                this.hidSelectedTab.Value = this.Server.UrlDecode(prevTab.Value);
            }
        }

        #endregion

        #region Branch&Account

        private void SetBranchAndAccountView()
        {
            this.txtPostback.Attributes["style"] = "display:none";
            bool editable = this.AccessControl.ApplicationTabView.Visible & this.AccessControl.ApplicationTabView.Editable;
            this.ddlCATBranch.Visible = this.ddlAccount.Visible = editable;

            if (editable)
            {
                DataTable accountTable = this.queryService.GetDicItemsByTypeName(DicType.ACCOUNT);
                this.ddlAccount.DataSource = accountTable;
                this.ddlAccount.DataTextField = "Description";
                this.ddlAccount.DataValueField = "DicItemKey";

                this.ddlAccount.DataBind();

                if (this.Application.Account != null)
                {
                    this.ddlAccount.SelectedValue = this.Application.Account;
                }

                this.ddlCATBranch.DataSource = this.queryService.GetCATBranchDepartments();
                this.ddlCATBranch.DataTextField = "DepartmentNameEN";
                this.ddlCATBranch.DataValueField = "DepartmentValue";
                this.ddlCATBranch.DataBind();
                // this.ddlCATBranch.Items.Insert(this.ddlCATBranch.Items.Count, new ListItem("Others", "OTH;0;0;OTH;OTH"));

                string v = this.Application.AllDept;

                if (string.IsNullOrEmpty(v))
                {
                    v = this.UserInfo.BD;
                }

                foreach (ListItem li in this.ddlCATBranch.Items.Cast<ListItem>().Where(li => ValueIncludes(li.Value, v)))
                {
                    li.Selected = true;
                    break;
                }

                this.secAccount.Visible = this.ddlAccount.Visible = this.ddlCATBranch.SelectedValue.StartsWith("Branch;", StringComparison.InvariantCultureIgnoreCase);
            }
            else
            {
                this.lblCATBranch.Text = this.Application.CATBranch;

                this.lblAccount.Text = this.Application.Account;

                this.secAccount.Visible = this.Application.Account.IsNotNullOrWhiteSpace();
            }
        }

        protected void ddlCATBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool visible = this.ddlCATBranch.SelectedValue.StartsWith("Branch;", StringComparison.InvariantCultureIgnoreCase);
            this.secAccount.Visible = visible;
            this.lblAccount.Visible = visible;
            this.ddlAccount.Visible = visible;

            this.ucApplicant.ChangeCODPPCheckPerson(Convert.ToInt32(this.ddlCATBranch.SelectedValue.Split(';')[2]));
        }

        #endregion

        #region BasicInfo

        private void SetBasicInfoView()
        {
            if (!this.AccessControl.BasicInfoTabView.Visible)
            {
                return;
            }

            this.tabBasicInfo.Visible = this.pnlBasicInfo.Visible = this.ucBasicInfo.Visible = true;
            this.ucBasicInfo.SessionKey = this.SessionKey;
            this.ucBasicInfo.CurrentUser = this.CurrentUser;

            if (Application.UrgentCaseComments.IsNotNullOrWhiteSpace())
            {
                this.ucUrgent.Visible = true;
                this.ucUrgent.SessionKey = this.SessionKey;
                this.ucUrgent.CurrentUser = this.CurrentUser;
            }


            if (!this.AccessControl.CommentTabView.Visible)
            {
                return;
            }

            this.ucComment.Visible = true;
            this.ucComment.Editable = this.AccessControl.CommentTabView.Editable;
            this.ucComment.SessionKey = this.SessionKey;
            this.ucComment.CurrentUser = this.CurrentUser;
        }

        #endregion

        #region Applicant

        private void SetApplicantView()
        {
            if (!this.AccessControl.ApplicantTabView.Visible)
            {
                return;
            }

            this.tabApplicant.Visible = this.pnlApplicant.Visible = this.ucApplicant.Visible = true;
            this.ucApplicant.SessionKey = this.SessionKey;
            this.ucApplicant.Editable = this.AccessControl.ApplicantTabView.Editable;
            this.ucApplicant.CurrentUser = this.CurrentUser;
        }

        #endregion Applicant

        #region Contract

        private void SetContractView()
        {
            this.tabContract.Visible = this.pnlContract.Visible = this.ucContract.Visible = this.AccessControl.ContractTabView.Visible;
            this.ucContract.SessionKey = this.SessionKey;
            this.ucContract.Editable = this.AccessControl.ContractTabView.Editable;
            this.ucContract.CurrentUser = this.CurrentUser;
        }

        #endregion

        #region Visit Places

        private void SetVisitPlacesView()
        {
            if (!this.AccessControl.ApplicationTabView.Visible)
            {
                return;
            }

            this.tabVisit.Visible = this.pnlVisit.Visible = this.ucVisit.Visible = true;
            this.ucVisit.SessionKey = this.SessionKey;
            this.ucVisit.Editable = this.AccessControl.ApplicationTabView.Editable;
            this.ucVisit.CurrentUser = this.CurrentUser;
        }

        #endregion

        #region Customers

        private void SetCustomerView()
        {
            if (!this.AccessControl.ApplicationTabView.Visible)
            {
                return;
            }

            this.tabCustomer.Visible = this.pnlCustomer.Visible = this.ucCustomer.Visible = true;
            this.ucCustomer.SessionKey = this.SessionKey;
            this.ucCustomer.Editable = this.AccessControl.ApplicationTabView.Editable;
            this.ucCustomer.CurrentUser = this.CurrentUser;
        }

        #endregion

        #region Alt Attendees

        private void SetAltAttendeeView()
        {
            if (!this.AccessControl.ApplicationTabView.Visible)
            {
                return;
            }

            this.tabAttendees.Visible = this.pnlAttendees.Visible = this.ucAltAttendee.Visible = true;
            this.ucAltAttendee.SessionKey = this.SessionKey;
            this.ucAltAttendee.Editable = this.AccessControl.ApplicationTabView.Editable;
            this.ucAltAttendee.CurrentUser = this.CurrentUser;
        }

        #endregion

        #region Quotation Attachment

        private void SetQuotAttchView()
        {
            // Tab 7
            this.tabQuotAttch.Visible = this.pnlQuotAttch.Visible = this.ucQuotAttch.Visible = this.AccessControl.QuotAttchTabView.Visible;
            this.ucQuotAttch.Editable = this.AccessControl.QuotAttchTabView.Editable;
            this.ucQuotAttch.CurrentUser = this.CurrentUser;
            this.ucQuotAttch.SessionKey = this.SessionKey;

            if (Application.UrgentCaseComments.IsNotNullOrWhiteSpace())
            {
                this.ucUrgent2.Visible = true;
                this.ucUrgent2.SessionKey = this.SessionKey;
                this.ucUrgent2.CurrentUser = this.CurrentUser;
            }
        }

        #endregion

        #region AftReturn

        private void SetAftReturnView()
        {
            bool tabVisible = this.AccessControl.AftReturnTabsView.Visible;

            this.tabFeedback.Visible = this.pnlFeedback.Visible = this.ucFeedback.Visible = tabVisible;
            this.ucAftAttchment.Visible = tabVisible;
            this.ucFeedback.SessionKey = this.ucAftAttchment.SessionKey = this.SessionKey;
            this.ucFeedback.Editable = this.ucAftAttchment.Editable = this.AccessControl.AftReturnTabsView.Editable;
            this.ucFeedback.CurrentUser = this.ucAftAttchment.CurrentUser = this.CurrentUser;
        }

        #endregion

        #region Attchments

        private void SetAttchView()
        {
            if (!this.AccessControl.ApplicationTabView.Visible)
            {
                return;
            }

            this.tabAttch.Visible = this.pnlAttch.Visible = this.ucAttachment.Visible = true;
            this.ucAttachment.Editable = this.AccessControl.ApplicationTabView.Editable;
            this.ucAttachment.SessionKey = this.SessionKey;
            this.ucAttachment.CurrentUser = this.CurrentUser;
        }

        #endregion

        #region Data Save

        private void SetActionType(string actionType)
        {
            this.ucApplicant.CurrentActionType = actionType;
            this.ucContract.CurrentActionType = actionType;
            this.ucCustomer.CurrentActionType = actionType;
            this.ucVisit.CurrentActionType = actionType;
            this.ucAltAttendee.CurrentActionType = actionType;
            this.ucAttachment.CurrentActionType = actionType;
            this.ucQuotAttch.CurrentActionType = actionType;
            this.ucFeedback.CurrentActionType = actionType;
            this.ucAftAttchment.CurrentActionType = actionType;
            this.ucComment.CurrentActionType = actionType;
        }

        private void SaveDraft()
        {
            EZVisitApplicationTableEntity entity = this.Application; //this.GetAppFormEntity();

            if (!entity.AppID.HasValue)
            {
                entity.RequesterID = this.UserInfo.EmployeeID;
                entity.RequesterNo = this.UserInfo.EmployeeNo;
                entity.RequesterNameEN = this.UserInfo.NameEN;
                entity.RequesterNameCN = this.UserInfo.NameChinese;
                entity.RequesterDept = this.queryService.GetDepartmentByID(this.UserInfo.Department.Value).Description;
                entity.RequesterOfficeTel = this.UserInfo.OfficePhone;
                entity.RequesterTitle = this.UserInfo.Title;
                entity.CreateAt = DateTime.Now;
                entity.CreateBy = this.CurrentUser;
                entity.IsEnabled = true;
                entity.Folio = this.GetNewFolio();
                EZVisitApplicationManager.Insert(entity);
                this.NewAppFormId = entity.AppID;
            }
            else
            {
                if (entity.Folio == null)
                {
                    entity.Folio = this.GetNewFolio();
                    EZVisitApplicationManager.Update(entity);
                }
            }
            string id = Request.QueryString[GetRequestParamKey_AppFormId()];
            int appFormId;
            bool res = int.TryParse(id, out appFormId);
            if (!res)
            {
                NewAppFormId = entity.AppID;
            }

            this.Application = entity;

            if (this.ucApplicant.Editable)
            {
                this.ucApplicant.Save(this.Application);
                this.ucContract.Save(this.Application);
                this.ucCustomer.Save(this.Application);
                this.ucVisit.Save(this.Application);
                this.ucAltAttendee.Save(this.Application);
                this.ucAttachment.Save(this.Application);
            }
        }

        private void SaveQuotAttch()
        {
            if (this.ucQuotAttch.Editable)
            {
                this.ucQuotAttch.Save(this.Application);
            }
        }

        private void SaveFNCContractInfo()
        {
            this.ucContract.Save(this.Application);
        }

        private void SaveFeedback()
        {
            if (this.ucFeedback.Editable)
            {
                this.ucFeedback.Save(this.Application);
                this.ucAftAttchment.Save(this.Application);
            }
        }

        private void SaveComment()
        {
            if (this.ucComment.Visible)
            {
                this.ucComment.Save(this.Application);
            }
        }

        /// <summary>
        ///   当前审批人审批通过后修改审批人和时间
        /// </summary>
        private void UpdateApproverAndDateWhenApproved(string actionType)
        {
            switch (actionType)
            {
                case K2ActionType.Save:
                    break;
                case K2ActionType.Submit:
                    break;
                case K2ActionType.Approve:
                    if (ValueIncludes(this.Application.CurrentStep, EZVisitActivityNameConsts.FNC_Controller) && ValueIncludes(this.Application.CurrentApprover, this.CurrentUser))
                    {
                        this.Application.FNCControllerDate = DateTime.Now;
                    }
                    else if (ValueIncludes(this.Application.CurrentStep, EZVisitActivityNameConsts.CEO_Delegation) && ValueIncludes(this.Application.CurrentApprover, this.CurrentUser))
                    {
                        this.Application.CEODelegationDate = DateTime.Now;
                    }
                    else if (ValueIncludes(this.Application.CurrentStep, EZVisitActivityNameConsts.LGD) && ValueIncludes(this.Application.CurrentApprover, this.CurrentUser))
                    {
                        this.Application.LGDDate = DateTime.Now;
                    }
                    break;
                case K2ActionType.Validate:
                    if (ValueIncludes(this.Application.CurrentStep, EZVisitActivityNameConsts.Dept_Head) && ValueIncludes(this.Application.CurrentApprover, this.CurrentUser))
                    {
                        this.Application.DeptHeadDate = DateTime.Now;
                    }
                    else if (ValueIncludes(this.Application.CurrentStep, EZVisitActivityNameConsts.COD_PP_Check_Person) && ValueIncludes(this.Application.CurrentApprover, this.CurrentUser))
                    {
                        this.Application.CODPPCheckPersonDate = DateTime.Now;
                    }
                    else if (ValueIncludes(this.Application.CurrentStep, EZVisitActivityNameConsts.COD_PP_Manager) && ValueIncludes(this.Application.CurrentApprover, this.CurrentUser))
                    {
                        this.Application.CODPPManagerDate = DateTime.Now;
                    }
                    else if (ValueIncludes(this.Application.CurrentStep, EZVisitActivityNameConsts.COD_PP_Head) && ValueIncludes(this.Application.CurrentApprover, this.CurrentUser))
                    {
                        this.Application.CODPPHeadDate = DateTime.Now;
                    }
                    else if (ValueIncludes(this.Application.CurrentStep, EZVisitActivityNameConsts.LGD_Check_Person) && ValueIncludes(this.Application.CurrentApprover, this.CurrentUser))
                    {
                        this.Application.LGDCheckPersonDate = DateTime.Now;
                    }
                    else if (ValueIncludes(this.Application.CurrentStep, EZVisitActivityNameConsts.Post_COD_PP_Check_Person) && ValueIncludes(this.Application.CurrentApprover, this.CurrentUser))
                    {
                        this.Application.AftCODPPChecPersonDate = DateTime.Now;
                    }
                    else if (ValueIncludes(this.Application.CurrentStep, EZVisitActivityNameConsts.Post_COD_PP_Manager) && ValueIncludes(this.Application.CurrentApprover, this.CurrentUser))
                    {
                        this.Application.AftCODPPManagerDate = DateTime.Now;
                    }
                    else if (ValueIncludes(this.Application.CurrentStep, EZVisitActivityNameConsts.Post_Dept_Head) && ValueIncludes(this.Application.CurrentApprover, this.CurrentUser))
                    {
                        this.Application.AftDeptHeadDate = DateTime.Now;
                    }
                    else if (ValueIncludes(this.Application.CurrentStep, EZVisitActivityNameConsts.Post_COD_PP_Head) && ValueIncludes(this.Application.CurrentApprover, this.CurrentUser))
                    {
                        this.Application.PostCODPPHeadDate = DateTime.Now;
                    }
                    break;
                case K2ActionType.Upload:
                    if (ValueIncludes(this.Application.CurrentStep, EZVisitActivityNameConsts.PDC) && ValueIncludes(this.Application.CurrentApprover, this.CurrentUser))
                    {
                        this.Application.PDCDate = DateTime.Now;
                    }
                    break;
                default:
                    break;
            }
            EZVisitApplicationManager.Update(this.Application);
        }

        #endregion

        #region Workflow Controller

        public override void RegisterWorkflowController()
        {
            this._workflowController = new EZVisitWorkflowController(this, this.GetAppForm(), this.GetMyActivity());
        }

        public override PlaceHolder GetPlaceHolder()
        {
            return this.phWorkflow;
        }

        public override void BuildFormArguments()
        {
            base.BuildFormArguments();
            Dictionary<string, object> formArguments = this.GetFormArguments();
            string TargetActivityName = this.GetCurrentTargetActivityName();

            formArguments[WorkflowKeyConsts.ModuleName] = "EZVisit Management";
            formArguments[EZVisitWorkflowKeyConsts.Applicant] = Convert.ToString(3637); //"di wan"3637
            formArguments[EZVisitActivityNameConsts.FNC_Controller] = this.GetDestination(EZVisitActivityNameConsts.FNC_Controller);
            formArguments[EZVisitActivityNameConsts.Dept_Head] = this.GetDestination(EZVisitActivityNameConsts.Dept_Head);

            int[] codppcp = this.GetDestination(EZVisitActivityNameConsts.COD_PP_Check_Person);
            if (codppcp.Length > 0)
            {
                formArguments[EZVisitWorkflowKeyConsts.CODPPCheckPerson] = codppcp[0];
            }
            else
            {
                formArguments[EZVisitWorkflowKeyConsts.CODPPCheckPerson] = -1;
            }
            int[] pdc = this.GetDestination(EZVisitActivityNameConsts.PDC);
            if (pdc.Length > 0)
            {
                formArguments[EZVisitWorkflowKeyConsts.PDC] = pdc[0];
            }
            else
            {
                formArguments[EZVisitWorkflowKeyConsts.PDC] = -1;

            }
            int[] codppcpmanager = this.GetDestination(EZVisitActivityNameConsts.COD_PP_Manager);
            if (codppcpmanager.Length > 0)
            {
                formArguments[EZVisitWorkflowKeyConsts.CODPPManager] = codppcpmanager[0];
            }
            else
            {
                formArguments[EZVisitWorkflowKeyConsts.CODPPManager] = -1;
            }

            formArguments[EZVisitActivityNameConsts.LGD] = this.GetDestination(EZVisitActivityNameConsts.LGD);

            formArguments[EZVisitActivityNameConsts.CEO_Delegation] = this.GetDestination(EZVisitActivityNameConsts.CEO_Delegation);
            formArguments[EZVisitActivityNameConsts.Post_Submission] = this.GetDestination(EZVisitActivityNameConsts.Post_Submission);
            formArguments[EZVisitActivityNameConsts.Post_COD_PP_Check_Person] = this.GetDestination(EZVisitActivityNameConsts.Post_COD_PP_Check_Person);
            formArguments[EZVisitActivityNameConsts.Post_Dept_Head] = this.GetDestination(EZVisitActivityNameConsts.Post_Dept_Head);
            formArguments[EZVisitActivityNameConsts.Post_Dept_Head] = this.GetDestination(EZVisitActivityNameConsts.Post_Dept_Head);
        }

        public override void InitActionPanel()
        {
            base.InitActionPanel();
            // Button btnWithdraw = this.GetActionPanel().GetActionButton(K2ActionType.Withdraw);
            // btnWithdraw.Visible = false;
        }

        public override void OnPreWorkflowLoadDone(EventArgs e)
        {
            base.OnPreWorkflowLoadDone(e);
        }

        public override void OnWorkflowLoadDone(EventArgs e)
        {
            base.OnWorkflowLoadDone(e);
        }

        public override string GetProcName()
        {
            return "EZVisit";
        }

        public override IAppForm GetAppForm()
        {
            return new EZVisitAppForm(this.GetAppFormEntity());
            //return GetEZVisitAppForm();
        }

        public EZVisitAppForm GetEZVisitAppForm()
        {
            EZVisitApplicationTableEntity entity = new EZVisitApplicationTableEntity();
            int? appFormId = this.GetAppFormId();
            if (appFormId.HasValue)
            {
                entity = EZVisitApplicationManager.SelectByKeys(appFormId.Value);
                this.Application.ProcessStatus = entity.ProcessStatus;
                this.Application.Status = entity.Status;
                this.Application.ProcInstId = entity.ProcInstId;
                this.Application.Readers = entity.Readers;
                this.Application.Folio = entity.Folio;
            }
            return new EZVisitAppForm(this.Application);
        }

        public override string GetRequestParamKey_AppFormId()
        {
            return base.GetRequestParamKey_AppFormId();
        }

        public override string GetRequestParamKey_MyActivityId()
        {
            return base.GetRequestParamKey_MyActivityId();
        }

        public override MyActivityTableEntity GetMyActivity()
        {
            return base.GetMyActivity();
        }

        public override IWorkflowActionPanel GetActionPanel()
        {
            return this.DefaultWorkflowActionPanel1;
        }

        public override IWorkflowControl GetProcessStampControl()
        {
            return base.GetProcessStampControl();
        }

        public override bool ExecuteAction(string actionType)
        {
            this.SetActionType(actionType);
            if (actionType.Equals(K2ActionType.AskForMore))
            {
                return true;
            }

            if (actionType.Equals(K2ActionType.Save))
            {
                this.SaveDraft();
                return true;
            }

            if (actionType.Equals(K2ActionType.Withdraw))
            {
                this.ucContract.Save(this.Application);
                this.ucQuotAttch.Save(this.Application);
                return true;
            }

            if (actionType.Equals(K2ActionType.PostSave))
            {
                this.SaveFeedback();
                return true;
            }

            this.Validate("ValidateSubmit");

            bool valid = this.Page.IsValid;

            if (actionType.Equals(K2ActionType.Submit))
            {
                this.SaveDraft();
                return valid;
            }

            if (valid)
            {
                switch (actionType)
                {
                    case K2ActionType.Resubmit:
                        this.SaveDraft();
                        break;
                    case K2ActionType.ReplyAskForMore:
                        this.SaveDraft();
                        this.SaveQuotAttch();
                        this.SaveComment();
                        this.SaveFeedback();
                        break;

                    case K2ActionType.Approve: // Validate FNC has entered the contract info.
                        this.SaveFNCContractInfo();
                        break;
                    case K2ActionType.Validate: // Validate CODPP Manager select a quotation.
                    case K2ActionType.Upload: // Validate PDC upload quotation.
                        this.SaveQuotAttch();
                        this.SaveComment();
                        break;
                    case K2ActionType.PostSubmit: // Valiate feedback
                        this.SaveFeedback();
                        break;
                    default:
                        break;
                }

                this.UpdateApproverAndDateWhenApproved(actionType);
            }

            return valid;
        }

        public override void ExecuteActionDone(string actionType)
        {
            //设置业务的流程步骤
            if (actionType != K2ActionType.Save && this.IsExcuteAction)
            {
                // EZVisitAppForm appform = this.GetAppForm() as EZVisitAppForm;
                EZVisitAppForm appform = this.GetEZVisitAppForm();
                this._myActivity = null;
                this._myActivityAssigned = false;
                Dictionary<string, object> formArguments = this.GetFormArguments();

                int procInstID = appform.ProcInstId;

                // procInstID = formArguments[WorkflowKeyConsts.AskformoreProcInstID] == null ? appform.ProcInstId : (int)formArguments[WorkflowKeyConsts.AskformoreProcInstID];
                //if (appform.ProcessStatus == ProcessStatusConsts.AskedForMore)
                //{
                MyActivityTableEntitySet ds = MyActivityManager.SelectByCondition(string.Format(" K2ProcInstID={0} and Status={1}", procInstID, (int)MyActivityStatus.Normal));
                string CurrentStep = string.Empty;
                string CurrentApprove = string.Empty;
                string FNC_Controller = string.Empty,
                       Dept_Head = string.Empty,
                       COD_PP_Check_Person = string.Empty,
                       PDC = string.Empty,
                       COD_PP_Manager = string.Empty,
                       CEO_Delegation = string.Empty,
                       COD_PP_Head = string.Empty,
                       LGD = string.Empty,
                       LGDCheckPerson = string.Empty,
                       PostCODPPManager = string.Empty,
                       PostCODPPHead = string.Empty,
                       FormURL = string.Empty;

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (appform.ProcessStatus == ProcessStatusConsts.AskedForMore)
                    {
                        if (CurrentStep.Length == 0)
                        {
                            CurrentStep = ds[i].TargetActivityName;
                        }
                        else
                        {
                            string tempstep = ";" + CurrentStep;
                            if (tempstep.IndexOf(";" + ds[i].TargetActivityName) == -1)
                            {
                                CurrentStep += ";" + ds[i].TargetActivityName;
                            }
                        }
                    }
                    else
                    {
                        if (CurrentStep.Length == 0)
                        {
                            CurrentStep = ds[i].K2ActivityName;
                        }
                        else
                        {
                            string tempstep = ";" + CurrentStep;
                            if (tempstep.IndexOf(";" + ds[i].K2ActivityName) == -1)
                            {
                                CurrentStep += ";" + ds[i].K2ActivityName;
                            }
                        }

                        string currentActivityName = ds[i].K2ActivityName;
                        switch (currentActivityName)
                        {
                            case EZVisitActivityNameConsts.FNC_Controller:
                                if (FNC_Controller.Length == 0)
                                {
                                    FNC_Controller = ds[i].OwnerEn;
                                }
                                else
                                {
                                    FNC_Controller += ";" + ds[i].OwnerEn;
                                }
                                appform.FNCController = FNC_Controller;
                                break;
                            case EZVisitActivityNameConsts.Dept_Head:
                                if (Dept_Head.Length == 0)
                                {
                                    Dept_Head = ds[i].OwnerEn;
                                }
                                else
                                {
                                    Dept_Head += ";" + ds[i].OwnerEn;
                                }
                                appform.DeptHead = Dept_Head;
                                break;
                            case EZVisitActivityNameConsts.PDC:
                                if (PDC.Length == 0)
                                {
                                    PDC = ds[i].OwnerEn;
                                }
                                else
                                {
                                    PDC += ";" + ds[i].OwnerEn;
                                }
                                appform.PDC = PDC;
                                break;
                            case EZVisitActivityNameConsts.COD_PP_Manager:
                                if (COD_PP_Manager.Length == 0)
                                {
                                    COD_PP_Manager = ds[i].OwnerEn;
                                }
                                else
                                {
                                    COD_PP_Manager += ";" + ds[i].OwnerEn;
                                }
                                appform.CODPPManager = COD_PP_Manager;
                                break;
                            case EZVisitActivityNameConsts.CEO_Delegation:
                                if (CEO_Delegation.Length == 0)
                                {
                                    CEO_Delegation = ds[i].OwnerEn;
                                }
                                else
                                {
                                    CEO_Delegation += ";" + ds[i].OwnerEn;
                                }
                                appform.CEODelegation = CEO_Delegation;
                                break;
                            case EZVisitActivityNameConsts.COD_PP_Head:
                                if (COD_PP_Head.Length == 0)
                                {
                                    COD_PP_Head = ds[i].OwnerEn;
                                }
                                else
                                {
                                    COD_PP_Head += ";" + ds[i].OwnerEn;
                                }
                                appform.CODPPHead = COD_PP_Head;
                                break;
                            case EZVisitActivityNameConsts.LGD_Check_Person:
                                if (LGDCheckPerson.Length == 0)
                                {
                                    LGDCheckPerson = ds[i].OwnerEn;
                                }
                                else
                                {
                                    LGDCheckPerson += ";" + ds[i].OwnerEn;
                                }
                                appform.LGDCheckPerson = LGDCheckPerson;
                                break;
                            case EZVisitActivityNameConsts.LGD:
                                if (LGD.Length == 0)
                                {
                                    LGD = ds[i].OwnerEn;
                                }
                                else
                                {
                                    LGD += ";" + ds[i].OwnerEn;
                                }
                                appform.LGD = LGD;
                                break;
                            case EZVisitActivityNameConsts.Post_COD_PP_Manager:

                                if (PostCODPPManager.Length == 0)
                                {
                                    PostCODPPManager = ds[i].OwnerEn;
                                }
                                else
                                {
                                    PostCODPPManager += ";" + ds[i].OwnerEn;
                                }
                                appform.PostCODPPManager = PostCODPPManager;
                                break;
                            case EZVisitActivityNameConsts.Post_COD_PP_Head:
                                if (PostCODPPHead.Length == 0)
                                {
                                    PostCODPPHead = ds[i].OwnerEn;
                                }
                                else
                                {
                                    PostCODPPHead += ";" + ds[i].OwnerEn;
                                }
                                appform.PostCODPPHead = PostCODPPHead;
                                break;
                            default:
                                break;
                        }
                    }
                    if (CurrentApprove.Length == 0)
                    {
                        CurrentApprove = ds[i].OwnerEn;
                    }
                    else
                    {
                        CurrentApprove += ";" + ds[i].OwnerEn;
                    }
                    FormURL = ds[i].FormURL;
                }
                appform.CurrentStep = CurrentStep;
                appform.CurrentApprover = CurrentApprove;
                if (string.IsNullOrEmpty(appform.FormURL))
                    appform.FormURL = FormURL;

                appform.UpdateEntity();
            }
            base.ExecuteActionDone(actionType);
        }

        private int[] GetDestination(string activityName)
        {
            var dt = new DataTable();
            var list = new List<int>();

            if (this.Application == null)
            {
                return new int[] { };
            }
            EmployeeTableEntity entity = EmployeeManager.SelectByKeys(this.Application.RequesterNo);

            switch (activityName)
            {
                case EZVisitActivityNameConsts.FNC_Controller:
                    list = this.GetUserInfosByRole("FNC Controller");
                    break;
                case EZVisitActivityNameConsts.Dept_Head:
                case EZVisitActivityNameConsts.Post_Dept_Head:

                    if (this.Application.Account != null && this.Application.Account.ToUpper() == "VIT")
                    {
                        list = this.GetUserInfosByRole("VIT Approver");
                    }
                    else if (entity != null)
                    {
                        list.Add(entity.ReportToID.Value);
                    }
                    break;
                case EZVisitActivityNameConsts.COD_PP_Check_Person:
                case EZVisitActivityNameConsts.Post_COD_PP_Check_Person:
                    if (this.Application.CODPPCheckPersonID.HasValue)
                    {
                        list.Add(this.Application.CODPPCheckPersonID.Value);
                    }
                    break;
                case EZVisitActivityNameConsts.PDC:
                    list = this.GetUserInfosByRole("PDC");
                    break;
                case EZVisitActivityNameConsts.COD_PP_Manager:
                    list = this.GetUserInfosByRole("COD-PP Manager");
                    break;
                case EZVisitActivityNameConsts.CEO_Delegation:
                    if (this.Application.Account != null && this.Application.Account.ToUpper() == "VIT")
                    {
                        list = this.GetUserInfosByRole("VIT Approver");
                    }
                    else if (this.Application.DepartmentName.GetValueOrDefault(0) != 0)
                    {
                        DepartmentTableEntity department = DepartmentManager.SelectByKeys(this.Application.DepartmentName.Value);
                        if (department.CEODelegation != null)
                        {
                            EmployeeTableEntity ceoentity = EmployeeManager.SelectByKeys(department.CEODelegation);
                            list.Add(ceoentity.EmployeeID.Value);
                        }
                    }
                    break;
                case EZVisitActivityNameConsts.LGD:
                    if (this.Application != null && this.Application.IsDomestic.HasValue && this.Application.IsDomestic.Value)
                    {
                        list = this.GetUserInfosByRole("LGD-Domestic");
                    }
                    else
                    {
                        list = this.GetUserInfosByRole("LGD-Oversea");
                    }
                    break;
                case EZVisitActivityNameConsts.Post_Submission:
                    if (this.Application.RequesterID.HasValue)
                    {
                        list.Add(this.Application.RequesterID.Value);
                    }
                    break;
                default:
                    list.Add(1);
                    break;
            }
            return list.ToArray();
        }

        #endregion
    }
}